import Vue from 'vue'
import Vuex from 'vuex'

// import mutations from'./mutations'
// import actions from './actions'
// import getters from './getters'
Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    cartList: []
  },
  getters: {
    cartLength(state) {
      return state.cartList.length
    },
    cartList(state) {
      return state.cartList
    },
    // checkedLength(state){
    //   return state.cartList.filter(item=>item.checked).length
    // }
  },
  // mutations,
  actions: {
    addCart(context, product) {
      return new Promise((resolve, reject) => {
        //product新添加的商品
        //1.查找之前数组中是否有该商品
        let oldProduct = context.state.cartList.find(item => item.iid === product.iid)

        //2.判断oldProduct
        if (oldProduct) {
          context.commit('addCounter', oldProduct)
          resolve('当前商品数量+1')
        } else {
          context.commit('addToCart', product)
          resolve('添加了新的商品')
        }
      })

    }
  },
  mutations: {
    addCounter(state, product) {
      product.count += 1
    },
    addToCart(state, product) {
      product.count = 1
      product.checked = false
      state.cartList.push(product)
    }
    // addCart(state, product) {
    //   //product新添加的商品
    //   //1.查找之前数组中是否有该商品
    //   let oldProduct = state.cartList.find(item => item.iid === product.iid)
    //   //2.判断oldProduct
    //   if (oldProduct) {
    //     oldProduct.count += 1
    //   } else {
    //     product.count=1
    //     product.checked = false
    //     state.cartList.push(product)
    //   }
    // }
  },
  modules: {}
})